package cn.zcltd.btg.set.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作工具类
 */
public class DbUtil {
    private static final Logger log = LoggerFactory.getLogger(DbUtil.class);

    /**
     * 执行sql语句
     *
     * @param conn   数据库连接
     * @param sql    sql
     * @param params params
     * @return int
     */
    public static int executeUpdate(Connection conn, String sql, Object... params) {
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i + 1, params[i]);
            }
            return pst.executeUpdate();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (pst != null) {
                    pst.close();
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return 0;
    }

    /**
     * 执行sql语句
     *
     * @param conn   数据库连接
     * @param sql    sql
     * @param params params
     * @return List
     */
    public static List<Map<String, Object>> executeQuery(Connection conn, String sql, Object... params) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            pst = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i + 1, params[i]);
            }
            rs = pst.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs.next()) {
                Map<String, Object> row = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(md.getColumnLabel(i), rs.getObject(i));
                }
                resultList.add(row);
            }
            return resultList;
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (pst != null) {
                    pst.close();
                }
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return resultList;
    }

    /**
     * 关闭数据库连接
     *
     * @param conn 数据库连接
     */
    public static void closeConnection(Connection conn) {
        try {
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
}